from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for

from info import constants
from info import db
from info.constants import *
from info.models import News, Category
from info.modules.profile import profile_blu
from info.utils.common import get_login_data
from info.utils.qiniu_storage import storage
from info.utils.response_code import RET


@profile_blu.route("/info")
@get_login_data
def info():
    user = g.user
    if not user:
        return redirect(url_for("index.index"))
    data = {
        "user_info": user.to_dict() if user else None
    }
    return render_template("news/user.html", data=data)


@profile_blu.route("/base_info", methods=["GET", "POST"])
@get_login_data
def base_info():
    user = g.user
    if not user:
        return redirect(url_for("index"))
    if request.method == "GET":
        data = {
            "user_info": user.to_dict() if user else None
        }
        return render_template("news/user_base_info.html", data=data)
    data_dict = request.json
    signature = data_dict.get("signature")
    nick_name = data_dict.get("nick_name")
    gender = data_dict.get("gender")

    if not all([signature, nick_name, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if gender not in ("MAN", "WOMAN"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 2、修改模型用户的数据 、提交
    user.signature = signature
    user.nick_name = nick_name
    user.gender = gender
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库操作失败")
    # 3、修改session中曾经保存的数据
    session["nick_name"] = nick_name
    # 4、返回成功
    return jsonify(errno=RET.OK, errmsg="保存成功")


@profile_blu.route("/pic_info", methods=["GET", "POST"])
@get_login_data
def pic_info():
    user = g.user
    if not user:
        return redirect(url_for("index.index"))
    if request.method == "GET":
        data = {
            "user_info": user.to_dict() if user else None
        }
        return render_template("news/user_pic_info.html", data=data)

    try:
        avatar_file = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="读取文件出错")

    try:
        url = storage(avatar_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")

    user.avatar_url = url
    try:
        db.session.commit()

    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存用户数据错误")

    return jsonify(errno=RET.OK, errmsg="okok哥们你赢了", data={"avatar_url": QINIU_DOMIN_PREFIX + url})


@profile_blu.route("/pass_info", methods=["GET", "POST"])
@get_login_data
def pass_info():
    user = g.user
    if not user:
        return redirect("/")
    if request.method == "GET":
        data = {
            "user_info": user.to_dict() if user else None
        }
        return render_template("news/user_pass_info.html", data=data)

    data_dict = request.json
    old_password = data_dict.get("old_password")
    new_password = data_dict.get("new_password")
    new_password2 = data_dict.get("new_password2")
    # 2、判空，校验   判空 、两密码是否一直、查询数据库
    if not all([old_password, new_password, new_password2]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if new_password != new_password2:
        return jsonify(errno=RET.PARAMERR, errmsg="两次密码不一致")

    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="密码错误")

    user.password = new_password
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库操作失败")
        # 4、返回结果
    return jsonify(errno=RET.OK, errmsg="操作成功")


@profile_blu.route("/collection")
@get_login_data
def collection():
    """
      渲染收藏新闻页面   GET


      1、获取参数、校验参数
      2、查询数据库 分页查询  user.collection_news
      3、新闻数据模型对象列表转换成字典列表   USER_NEWS_PAGE_MAX_COUNT
      4、返回数据 ：  新闻字典里列表、 总页数、当前页
      """
    user = g.user
    if not user:
        return redirect(url_for("index.index"))
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    cur_coll_news = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.collection_news.paginate(p, constants.USER_NEWS_PAGE_MAX_COUNT,
                                                 False)  # 第一个参数  当前页    第二个参数每一页多少条数据来分   第三个参数是 不要报错
        print(paginate.page)
        cur_coll_news = paginate.items  # 当前页的数据
        current_page = paginate.page  # 当前页数
        total_page = paginate.pages  # 总页数
    except Exception as e:
        current_app.logger.error(e)

    cur_coll_news_list = []
    for i in cur_coll_news:
        cur_coll_news_list.append(i.to_dict())

    data = {
        "cur_coll_news_list": cur_coll_news_list,
        "current_page": current_page,
        "total_page": total_page
    }

    return render_template("news/user_collection.html", data=data)


@profile_blu.route("/news_list", methods=["GET"])
@get_login_data
def news_list():
    """
    渲染用户发布过的新闻页面   GET


    1、获取参数、校验参数
    2、查询数据库 分页查询
    3、新闻数据模型对象列表转换成字典列表
    4、返回数据 ：  新闻字典里列表、 总页数、当前页
    """

    # 获取登录用户信息
    user = g.user
    if not user:
        # 重定向到首页
        return redirect("/")

    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    cur_news_list = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).order_by(News.create_time.desc()).paginate(p, constants.USER_NEWS_PAGE_MAX_COUNT,
                                                                       False)
        # 第一个参数  当前页    第二个参数每一页多少条数据来分   第三个参数是 不要报错
        cur_news_list = paginate.items  # 当前页的数据
        current_page = paginate.page  # 当前页数
        total_page = paginate.pages  # 总页数
    except Exception as e:
        current_app.logger.error(e)

    cur_user_news_list = []
    for i in cur_news_list:
        cur_user_news_list.append(i.to_review_dict())

    data = {
        "cur_user_news_list": cur_user_news_list,
        "current_page": current_page,
        "total_page": total_page
    }

    return render_template("news/user_news_list.html", data=data)


@profile_blu.route("/news_release", methods=["POST", "GET"])
@get_login_data
def news_release():
    """
    渲染发布新闻页面   GET


    处理发布新闻请求  POST
    1、获取参数判空
    2、上传图片文件到骑牛
    3、创建新闻模型对象  News()  字段先赋值  status 1
    4、提交数据
    5、返回成功

    """
    user = g.user
    if not user:
        redirect("/")

    if request.method == "GET":

        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        data = {
            "user_info": user.to_dict() if user else None,
            "categories": categories
        }
        return render_template("news/user_news_release.html", data=data)

    data_dict = request.form
    title = data_dict.get("title")  # 标题
    category_id = data_dict.get("category_id")  # 分类id
    digest = data_dict.get("digest")  # 摘要
    content = data_dict.get("content")  # 新闻内容
    index_image = request.files.get("index_image")  # 获取图片

    if not all([title, category_id, digest, content, index_image]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        index_image = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        pic_url_key = storage(index_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="图片上传出错")

    news = News()
    news.title = title
    news.category_id = int(category_id)
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + pic_url_key
    news.digest = digest
    news.content = content
    news.status = 1
    news.user_id = user.id
    news.source = "个人发布"
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库操作失败")
    return jsonify(errno=RET.OK, errmsg="发布成功，待审核")
